const { Op } = require('sequelize');
const { Order, OrderItem, Product, User, PointsTransaction, sequelize } = require('../models');
const pointsService = require('./pointsService');
const logger = require('../utils/logger');

class OrderManagementService {
  /**
   * 获取订单列表（管理后台）
   */
  async getOrderList(options = {}) {
    try {
      const {
        page = 1,
        limit = 20,
        search,
        status,
        paymentStatus,
        paymentMethod,
        userId,
        startDate,
        endDate,
        sortBy = 'createdAt',
        sortOrder = 'DESC'
      } = options;

      const where = {};
      
      // 搜索条件
      if (search) {
        where[Op.or] = [
          { orderNumber: { [Op.like]: `%${search}%` } },
          { '$User.phone$': { [Op.like]: `%${search}%` } },
          { '$User.nickname$': { [Op.like]: `%${search}%` } }
        ];
      }

      // 筛选条件
      if (status) where.status = status;
      if (paymentStatus) where.paymentStatus = paymentStatus;
      if (paymentMethod) where.paymentMethod = paymentMethod;
      if (userId) where.userId = userId;

      // 日期范围筛选
      if (startDate || endDate) {
        where.createdAt = {};
        if (startDate) {
          where.createdAt[Op.gte] = new Date(startDate);
        }
        if (endDate) {
          where.createdAt[Op.lte] = new Date(endDate);
        }
      }

      const { count, rows } = await Order.findAndCountAll({
        where,
        include: [
          {
            model: User,
            as: 'User', // 添加别名
            attributes: ['id', 'phone', 'nickname', 'avatar']
          }
        ],
        limit: parseInt(limit),
        offset: (parseInt(page) - 1) * parseInt(limit),
        order: [[sortBy, sortOrder.toUpperCase()]],
        distinct: true
      });

      return {
        orders: rows,
        pagination: {
          current: parseInt(page),
          total: Math.ceil(count / limit),
          pageSize: parseInt(limit),
          totalItems: count
        }
      };
    } catch (error) {
      logger.error('Get order list failed:', error);
      throw error;
    }
  }

  /**
   * 获取订单详情（管理后台）
   */
  async getOrderById(orderId) {
    try {
      const order = await Order.findByPk(orderId, {
        include: [
          {
            model: User,
            as: 'User',
            attributes: ['id', 'phone', 'nickname', 'avatar', 'memberLevel']
          }
        ]
      });

      if (!order) {
        throw new Error('订单不存在');
      }

      // 获取订单相关的积分记录
      const pointsRecords = await PointsTransaction.findAll({
        where: {
          userId: order.userId,
          [Op.or]: [
            { description: { [Op.like]: `%${order.orderNumber}%` } },
            { relatedId: orderId, source: { [Op.in]: ['order_complete', 'order_refund'] } }
          ]
        },
        order: [['createdAt', 'DESC']]
      });

      return {
        order,
        pointsRecords
      };
    } catch (error) {
      logger.error('Get order by id failed:', error);
      throw error;
    }
  }

  /**
   * 更新订单状态
   */
  async updateOrderStatus(orderId, newStatus, operatorId, notes) {
    const transaction = await sequelize.transaction();
    
    try {
      const order = await Order.findByPk(orderId, { transaction });
      
      if (!order) {
        throw new Error('订单不存在');
      }

      const oldStatus = order.status;

      // 验证状态转换的合法性
      if (!this.isValidStatusTransition(oldStatus, newStatus)) {
        throw new Error(`不能从 ${oldStatus} 状态转换到 ${newStatus} 状态`);
      }

      // 更新订单状态
      const updateData = {
        status: newStatus,
        adminNotes: notes || order.adminNotes
      };

      // 根据新状态设置相应的时间戳
      if (newStatus === 'completed') {
        updateData.actualCompletionTime = new Date();
        updateData.paymentStatus = 'paid';
        
        // 订单完成时给用户增加积分
        if (order.pointsEarned > 0) {
          await pointsService.addPoints(order.userId, order.pointsEarned, {
            type: 'order_complete',
            description: `订单完成奖励 - ${order.orderNumber}`,
            relatedId: orderId
          });
        }
      } else if (newStatus === 'cancelled') {
        // 取消订单时退还积分
        if (order.pointsUsed > 0) {
          await pointsService.addPoints(order.userId, order.pointsUsed, {
            type: 'order_refund',
            description: `订单取消退款 - ${order.orderNumber}`,
            relatedId: orderId
          });
        }
      }

      await order.update(updateData, { transaction });

      await transaction.commit();

      logger.info(`管理员 ${operatorId} 将订单 ${orderId} 状态从 ${oldStatus} 更新为 ${newStatus}`);

      return order;
    } catch (error) {
      await transaction.rollback();
      logger.error('Update order status failed:', error);
      throw error;
    }
  }

  /**
   * 处理订单退款
   */
  async processRefund(orderId, refundAmount, refundReason, operatorId) {
    const transaction = await sequelize.transaction();
    
    try {
      const order = await Order.findByPk(orderId, { transaction });
      
      if (!order) {
        throw new Error('订单不存在');
      }

      if (order.paymentStatus === 'refunded') {
        throw new Error('订单已经退款');
      }

      if (refundAmount > order.finalAmount) {
        throw new Error('退款金额不能超过订单金额');
      }

      // 更新订单状态
      await order.update({
        paymentStatus: 'refunded',
        status: 'cancelled',
        adminNotes: `${order.adminNotes || ''}\n退款原因：${refundReason}`
      }, { transaction });

      // 如果使用了积分，退还积分
      if (order.pointsUsed > 0) {
        await pointsService.addPoints(order.userId, order.pointsUsed, {
          type: 'order_refund',
          description: `订单退款 - ${order.orderNumber}`,
          relatedId: orderId
        });
      }

      await transaction.commit();

      logger.info(`管理员 ${operatorId} 处理订单 ${orderId} 退款，金额：${refundAmount}`);

      return order;
    } catch (error) {
      await transaction.rollback();
      logger.error('Process refund failed:', error);
      throw error;
    }
  }

  /**
   * 批量更新订单状态
   */
  async batchUpdateOrders(orderIds, updateData, operatorId) {
    const transaction = await sequelize.transaction();
    
    try {
      const { status, paymentStatus } = updateData;
      const updateFields = {};

      if (status) updateFields.status = status;
      if (paymentStatus) updateFields.paymentStatus = paymentStatus;

      await Order.update(updateFields, {
        where: {
          id: { [Op.in]: orderIds }
        },
        transaction
      });

      await transaction.commit();

      logger.info(`管理员 ${operatorId} 批量更新了 ${orderIds.length} 个订单`);

      return true;
    } catch (error) {
      await transaction.rollback();
      logger.error('Batch update orders failed:', error);
      throw error;
    }
  }

  /**
   * 获取订单统计概览
   */
  async getOrderOverview(days = 30) {
    try {
      const startDate = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
      const today = new Date();
      today.setHours(0, 0, 0, 0);

      const [
        totalOrders,
        todayOrders,
        recentOrders,
        pendingOrders,
        processingOrders,
        completedOrders,
        cancelledOrders,
        totalRevenue,
        recentRevenue,
        avgOrderValue
      ] = await Promise.all([
        Order.count(),
        Order.count({ where: { createdAt: { [Op.gte]: today } } }),
        Order.count({ where: { createdAt: { [Op.gte]: startDate } } }),
        Order.count({ where: { status: 'pending' } }),
        Order.count({ where: { status: { [Op.in]: ['confirmed', 'processing', 'printing'] } } }),
        Order.count({ where: { status: 'completed' } }),
        Order.count({ where: { status: 'cancelled' } }),
        Order.sum('finalAmount', { where: { status: 'completed' } }) || 0,
        Order.sum('finalAmount', { 
          where: { 
            status: 'completed',
            createdAt: { [Op.gte]: startDate }
          } 
        }) || 0,
        Order.findOne({
          attributes: [
            [sequelize.fn('AVG', sequelize.col('finalAmount')), 'avgValue']
          ],
          where: { status: 'completed' },
          raw: true
        })
      ]);

      return {
        totalOrders,
        todayOrders,
        recentOrders,
        pendingOrders,
        processingOrders,
        completedOrders,
        cancelledOrders,
        totalRevenue,
        recentRevenue,
        avgOrderValue: parseFloat(avgOrderValue?.avgValue || 0)
      };
    } catch (error) {
      logger.error('Get order overview failed:', error);
      throw error;
    }
  }

  /**
   * 获取订单趋势统计
   */
  async getOrderTrends(days = 30) {
    try {
      const startDate = new Date(Date.now() - days * 24 * 60 * 60 * 1000);

      const trends = await Order.findAll({
        attributes: [
          [sequelize.fn('DATE', sequelize.col('createdAt')), 'date'],
          [sequelize.fn('COUNT', sequelize.col('id')), 'orderCount'],
          [sequelize.fn('SUM', sequelize.col('finalAmount')), 'revenue']
        ],
        where: {
          createdAt: { [Op.gte]: startDate }
        },
        group: [sequelize.fn('DATE', sequelize.col('createdAt'))],
        order: [[sequelize.fn('DATE', sequelize.col('createdAt')), 'ASC']],
        raw: true
      });

      return trends.map(trend => ({
        date: trend.date,
        orderCount: parseInt(trend.orderCount),
        revenue: parseFloat(trend.revenue || 0)
      }));
    } catch (error) {
      logger.error('Get order trends failed:', error);
      throw error;
    }
  }

  /**
   * 异常订单检测
   */
  async getAbnormalOrders() {
    try {
      const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
      const threeDaysAgo = new Date(Date.now() - 3 * 24 * 60 * 60 * 1000);

      const [
        longPendingOrders,
        highValueOrders,
        frequentCancelOrders
      ] = await Promise.all([
        // 长时间待处理订单
        Order.findAll({
          where: {
            status: 'pending',
            createdAt: { [Op.lt]: oneDayAgo }
          },
          include: [
            {
              model: User,
              as: 'User',
              attributes: ['id', 'phone', 'nickname']
            }
          ],
          limit: 10
        }),

        // 高价值订单
        Order.findAll({
          where: {
            finalAmount: { [Op.gt]: 1000 },
            status: { [Op.in]: ['pending', 'confirmed'] }
          },
          include: [
            {
              model: User,
              as: 'User',
              attributes: ['id', 'phone', 'nickname']
            }
          ],
          limit: 10
        }),

        // 频繁取消订单的用户
        Order.findAll({
          attributes: [
            'userId',
            [sequelize.fn('COUNT', sequelize.col('id')), 'cancelCount']
          ],
          where: {
            status: 'cancelled',
            createdAt: { [Op.gte]: threeDaysAgo }
          },
          group: ['userId'],
          having: sequelize.where(sequelize.fn('COUNT', sequelize.col('id')), Op.gt, 3),
          include: [
            {
              model: User,
              as: 'User',
              attributes: ['id', 'phone', 'nickname']
            }
          ],
          raw: false
        })
      ]);

      return {
        longPendingOrders,
        highValueOrders,
        frequentCancelOrders
      };
    } catch (error) {
      logger.error('Get abnormal orders failed:', error);
      throw error;
    }
  }

  /**
   * 导出订单数据
   */
  async exportOrders(options = {}) {
    try {
      const {
        search,
        status,
        paymentStatus,
        startDate,
        endDate
      } = options;

      const where = {};
      
      if (search) {
        where[Op.or] = [
          { orderNumber: { [Op.like]: `%${search}%` } }
        ];
      }

      if (status) where.status = status;
      if (paymentStatus) where.paymentStatus = paymentStatus;

      if (startDate || endDate) {
        where.createdAt = {};
        if (startDate) {
          where.createdAt[Op.gte] = new Date(startDate);
        }
        if (endDate) {
          where.createdAt[Op.lte] = new Date(endDate);
        }
      }

      const orders = await Order.findAll({
        where,
        include: [
          {
            model: User,
            as: 'User',
            attributes: ['phone', 'nickname']
          }
        ],
        order: [['createdAt', 'DESC']]
      });

      // 格式化导出数据
      const exportData = orders.map(order => ({
        订单号: order.orderNumber,
        用户手机: order.User?.phone || '',
        用户昵称: order.User?.nickname || '',
        订单金额: order.totalAmount,
        折扣金额: order.discountAmount,
        实付金额: order.finalAmount,
        使用积分: order.pointsUsed,
        获得积分: order.pointsEarned,
        订单状态: this.getStatusText(order.status),
        支付状态: this.getPaymentStatusText(order.paymentStatus),
        支付方式: this.getPaymentMethodText(order.paymentMethod),
        创建时间: order.createdAt,
        完成时间: order.actualCompletionTime || '',
        备注: order.notes || '',
        管理员备注: order.adminNotes || ''
      }));

      return exportData;
    } catch (error) {
      logger.error('Export orders failed:', error);
      throw error;
    }
  }

  /**
   * 验证状态转换是否合法
   */
  isValidStatusTransition(fromStatus, toStatus) {
    const validTransitions = {
      'pending': ['confirmed', 'cancelled'],
      'confirmed': ['processing', 'cancelled'],
      'processing': ['printing', 'cancelled'],
      'printing': ['completed', 'cancelled'],
      'completed': [], // 已完成的订单不能再转换
      'cancelled': [] // 已取消的订单不能再转换
    };

    return validTransitions[fromStatus]?.includes(toStatus) || false;
  }

  /**
   * 获取状态文本
   */
  getStatusText(status) {
    const statusMap = {
      'pending': '待确认',
      'confirmed': '已确认',
      'processing': '处理中',
      'printing': '打印中',
      'completed': '已完成',
      'cancelled': '已取消'
    };
    return statusMap[status] || status;
  }

  /**
   * 获取支付状态文本
   */
  getPaymentStatusText(paymentStatus) {
    const statusMap = {
      'unpaid': '未支付',
      'paid': '已支付',
      'refunded': '已退款'
    };
    return statusMap[paymentStatus] || paymentStatus;
  }

  /**
   * 获取支付方式文本
   */
  getPaymentMethodText(paymentMethod) {
    const methodMap = {
      'points': '积分支付',
      'wechat': '微信支付',
      'alipay': '支付宝',
      'cash': '现金支付'
    };
    return methodMap[paymentMethod] || paymentMethod || '';
  }
}

module.exports = new OrderManagementService();